package com.mingqijia.gassafety.console.openapi;


import cn.hutool.http.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.webserver.service.BusinessNoticeService;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;


@Slf4j
@Api(tags = "开放接口")
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/console/v1/openapi", produces = MediaType.APPLICATION_JSON_VALUE)
public class AutomaticController {

    private final CompanyService companyService;
    private final BusinessNoticeService noticeService;

    private final static String TEMPLATE = "https://%s/api/console/v1/dictionaries/duplicate/%s";


    // 字典的自动填充（按企业）
    @GetMapping("/settings/duplicate")
    @ApiOperation(value = "自动填充新增企业的字典数据", notes = "自动填充新增企业的字典数据")
    @Transactional(rollbackFor = Exception.class)
    public void duplicateDictBySpId() {
        if (!Constants.PLATFORM_SP.equals(ApplicationUtils.getHeaderSpId())) {
            throw new GlobalAuthenticationException("只能在集团下执行此功能");
        }
        // 1. 查到哪些企业没有构建自己的个性化字典配置
        List<String> spIds = companyService.findSpIdWithNoDict();

        // 2. 调用字典复制接口，构建企业字典配置
        for (String spId : spIds) {
            duplicateDictionaries(spId);
            noticeService.duplicateNotices(spId);
//            break;
        }
    }


    private void duplicateDictionaries(String spId) {
        log.info("执行企业字典数据复制spId={}]...", spId);

        HttpRequest request = HttpUtil.createRequest(Method.GET,
                String.format(TEMPLATE, ApplicationUtils.getRequest().getServerName(), spId));
        request.header(Header.AUTHORIZATION,
                ApplicationUtils.getAttrFromHeader(Header.AUTHORIZATION.getValue()));
        doHttpRequest(request);

        log.info("企业字典数据复制完成。");
    }

    private void doHttpRequest(HttpRequest request) {
        HttpResponse response = request.execute();
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            log.error("调用{}失败, 返回：{}", request.getUrl(), response.body());
            throw new GlobalAuthenticationException(response.body());
        }
        log.info("调用{}, 返回:{}", request.getUrl(), response.body());
        JSONObject result = JSONUtil.parseObj(response.body());
        if (!Objects.equals(result.getInt("code"), Constants.INT_ZERO)) {
            log.error("数据请求失败：{}", response.body());
            throw new GlobalAuthenticationException(result.getStr("msg"));
        }
    }
}
